# -*- coding: utf-8 -*-
"""
@time：  2021/06/21  19:59
@Auto：Mr. xingye  993843278
@Company 星野训练营 99384378@qq.com
@Function: 邮箱配置库

"""

from email.header import Header
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from common.Logger import logger,path
from common.result import Result
import yaml




class Mail:
    """
        powered by Mr Xingye
        at 2021-06-21
        用来获取配置并发送邮件
    """

    def __init__(self):
        # 读取配置文件
        with open(file=path + '/conf/conf.yaml',mode='r',encoding='utf-8') as file:
            self.mail_info = yaml.load(stream=file,Loader=yaml.FullLoader)['mail']

        # 获取模板
        with open(file=path + '/conf/' +self.mail_info['mailmodule'],mode='r',encoding='utf8') as file:
            self.mail_info['mailtext'] = file.read()
            self.text = self.mail_info['mailtext']
        # 发件人
        self.mail_info['from'] = self.mail_info['username']
        # smtp服务器域名，截取域名，然后拼上smtp.
        self.mail_info['hostname'] = 'smtp.' + self.mail_info['username']\
        [self.mail_info['username'].rfind('@') +1:self.mail_info['username'].__len__()]

        # 附件内容
        self.mail_info['filepaths'] = []
        self.mail_info['filenames'] = []

        self.res = Result()


    def send(self,text):
        # 这里使用SMTP_SSL就是默认使用465端口，如果发送失败，可以使用587
        smtp = SMTP_SSL(self.mail_info['hostname'])  #port=587
        smtp.set_debuglevel(2)

        ''' SMTP 'ehlo' command.
        Hostname to send for this command defaults to the FQDN of the local
        host.
        '''
        smtp.ehlo(self.mail_info['hostname'])
        smtp.login(self.mail_info['username'],self.mail_info['password'])

        # 普通HTML邮件
        # msg = MIMEText(text,'html',self.mail_info['mail_encoding'])

        # 支持附件的邮件
        msg = MIMEMultipart()
        msg.attach(MIMEText(text,'html',self.mail_info['mail_encoding']))
        msg['Subject'] =Header(self.mail_info['mail_subject'],self.mail_info['mail_encoding'])
        # msg['from'] = self.mail_info['from']
        # 添加自定义昵称
        h = Header(self.mail_info['mailnick'], 'utf-8')
        h.append('<' + self.mail_info['from'] + '>', 'ascii')
        msg['from'] = h

        # logger.debug(self.mail_info)
        logger.debug(text)
        # logger.debug(msg)
        msg['to'] = ','.join(self.mail_info['to'])
        msg['cc'] = ','.join(self.mail_info['cc'])
        print(msg)
        receive = self.mail_info['to']
        receive += self.mail_info['cc']


        # 添加附件
        for i in range(len(self.mail_info['filepaths'])):
            att1 = MIMEText(open(self.mail_info['filepaths'][i], 'rb').read(), 'base64', 'utf-8')
            att1['Content-Type'] = 'application/octet-stream'
            # att1['Content-Disposition'] = 'attachment; filename= "'+self.mail_info['filenames'][i]+'"'
            att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', self.mail_info['filenames'][i]))

            msg.attach(att1)

        try:
            smtp.sendmail(self.mail_info['from'], receive, msg.as_string())
            smtp.quit()
            logger.info('邮件发送成功')
        except Exception as e:
            logger.error('邮件发送失败：')
            logger.exception(e)

    def get_summary(self, result_path):
        """
        获取邮件汇总信息
        :param result_path: 结果文件路径
        :return:
        """
        summary = self.res.get_res(result_path)
        logger.info(summary)
        text = self.mail_info['mailtext']
        # 替换汇总信息
        for key in summary.keys():
            if summary[key] == "PASS":
                text = text.replace(
                    '<font style="font-weight: bold;font-size: 14px;color: scolor;">status</font>',
                    '<font style="font-weight: bold;font-size: 14px;color: #00d800;">PASS</font>')
            elif summary[key] == "FAIL":
                text = text.replace(
                    '<font style="font-weight: bold;font-size: 14px;color: scolor;">status</font>',
                    '<font style="font-weight: bold;font-size: 14px;color: red;">FAIL</font>')
            else:
                text = text.replace(key, summary[key])

        return text

    def get_details(self, result_path):
        """
        获取详解结果列表
        :param result_path: 结果文件路径
        :return:
        """
        groups = self.res.get_groups(result_path)
        # logger.info(groups)

        # 获取分组显示
        tr = '<tr><td width="100" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">分组信息</td><td width="80" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">用例总数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">通过数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc; color:scolor;">状态</td></tr>'
        trs = ""
        for i in range(len(groups)):
            tmp = tr.replace('分组信息', str(groups[i][0]))
            tmp = tmp.replace('用例总数', str(groups[i][1]))
            tmp = tmp.replace('通过数', str(groups[i][2]))
            if str(groups[i][3]) == "PASS":
                tmp = tmp.replace('scolor', '#00d800')
            else:
                tmp = tmp.replace('scolor', 'red')
            tmp = tmp.replace('状态', str(groups[i][3]))
            trs = trs + tmp

        return trs


if __name__ == '__main__':

    mail = Mail()
    text = mail.get_summary(path + '/lib/接口测试用例result.xlsx')
    trs = mail.get_details(path + '/lib/接口测试用例result.xlsx')
    text = text.replace('mailbody', trs)
    print(text)
    mail.send(text)